package com.weiaibenpao.demo.chislim.ui.activity.moment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.api.Url;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.bean.EventBusBean;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.ReleasePresenter;
import com.weiaibenpao.demo.chislim.ui.adapter.ReleaseAdapter;
import com.weiaibenpao.demo.chislim.utils.LoadingDialogUtils;
import com.weiaibenpao.demo.chislim.view.ReleaseView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class ReleaseActivity extends BaseActivity<ReleaseView,ReleasePresenter> implements ReleaseView {

    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_limit_size)
    TextView tvLimitSize;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    public final static int REQUEST_POST_MOMENT = 110;
    private InputMethodManager imm;
    private AlertDialog dialog;
    private ReleaseAdapter releaseAdapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private List<String> urlList;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private int userId;
    private final static int UP_SUCCESS = 12000;

    private OkHttpClient client;
   private Request request;
    private String token;
    private List<String> qiNiuList;
    @SuppressLint("HandlerLeak")
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    if (!TextUtils.isEmpty(token)){
                        for (int i = 0; i < selectList.size(); i++) {
                            uploadImageToQiNiu(selectList.get(i).getPath());
                            Logger.e("selectList.get(i).getPath() "+selectList.get(i).getPath());
                        }
                    }else {
                        Toast.makeText(ReleaseActivity.this,"请查看网络是否出错",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case UP_SUCCESS:
                    for (int i = 0; i < qiNiuList.size(); i++) {
                        if (i==qiNiuList.size()-1){
                            buffer.append(qiNiuList.get(i));
                        }else {
                            buffer.append(qiNiuList.get(i)).append(",");
                        }
                    }
                    mPresenter.postHumor(userId,!TextUtils.isEmpty(etContent.getText().toString())?etContent.getText().toString():"",
                            buffer.toString(),"",tvLocation.getText().toString());

            }
        }
    };
    private LoadingDialogUtils.Builder builder;
    private StringBuffer buffer;

    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_release;
    }

    @Override
    public ReleasePresenter initPresenter() {
        return new ReleasePresenter();
    }

    @Override
    public void init(Bundle savedInstanceState) {
        userId = UserPreferences.getInstance().getInt(UserPreferences.USER_ID);
        EventBus.getDefault().register(this);
        initMap();
        imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        urlList=new ArrayList<>();
        qiNiuList=new ArrayList<>();
        buffer = new StringBuffer();

        initAdapter();
        /**
         * 设置监听
         */
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() > 250) {
                    s.delete(250, s.length());
                }
                tvLimitSize.setText(s.length() + "/120");
            }


        });
        /**
         * 七牛
         */
        //发送七牛请求
        client=new OkHttpClient();
         request=new Request.Builder().url(Url.TOKEN_URL) .get()
                .build();
        builder = new LoadingDialogUtils.Builder(this).setTitle("正在加载...");
    }

    private void initAdapter() {

        releaseAdapter = new ReleaseAdapter(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(releaseAdapter);
        releaseAdapter.setOnItemClickListener(new ReleaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                /**
                 * 点击查看大图
                 */
                initData();
                LookHugePhotoActivity.externalPicturePreview(ReleaseActivity.this,position,urlList,1);

            }

            @Override
            public void onAddClick() {
                checkPerMissions();
            }
        });
    }
    private void initData() {
        urlList.clear();
        for (int i = 0; i < selectList.size(); i++) {
            if (!TextUtils.isEmpty(selectList.get(i).getPath())) urlList.add(selectList.get(i).getPath());
        }
    }
    public static void startSelf(Context context) {
        Intent intent = new Intent(context, ReleaseActivity.class);
        context.startActivity(intent);
    }

    public static void startSelf(Context context, Fragment fragment) {
        Intent intent = new Intent(context, ReleaseActivity.class);
        fragment.startActivityForResult(intent, REQUEST_POST_MOMENT);
    }

    private void startCamera() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(ReleaseActivity.this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(9)// 最大图片选择数量 int
                .isCamera(true)// 是否显示拍照按钮 true or false
                .previewImage(true)// 是否可预览图片 true or false
                .withAspectRatio(1,1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .selectionMedia(selectList)// 是否传入已选图片
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code


    }
    //初始化定位信息
    private void initMap() {
        mLocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置返回地址信息，默认为true


        //设置定位监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        String pro = amapLocation.getProvince();//省信息
                        String city = amapLocation.getCity();//城市信息
                        String dist = amapLocation.getDistrict();//城区信息
                        tvLocation.setText(pro + city + dist);

                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Logger.e("location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置是否只定位一次,默认为false

        mLocationClient.startLocation();
    }

    /**
     * 权限检查
     *
     * @param
     */
    public void checkPerMissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            startCamera();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startCamera();
        } else {
            showDialogTipUserGoToAppSetting();
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSetting() {
        String set = "请在-应用设置-权限管理\n允许东极圈使用相机权限，确保该功能的正常使用";
        dialog = new AlertDialog.Builder(this)
                .setTitle("相机权限不可用")
                .setMessage(set)
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(ReleaseActivity.this, "请在应用管理中打开相关访问权限，确保该功能的正常使用", Toast.LENGTH_SHORT).show();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            switch (requestCode) {
                case 123:
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        // 检查该权限是否已经获取
                        int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (i != PackageManager.PERMISSION_GRANTED) {
                            // 提示用户应该去应用设置界面手动开启权限
                            showDialogTipUserGoToAppSetting();
                        } else {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }

                        }
                        break;
                    }
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                  selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    releaseAdapter.addDate(selectList);
                    break;
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @OnClick({R.id.btn_release, R.id.left_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_image:
                finish();
                break;
            case R.id.btn_release:
                    release();
                    break;
        }
    }

    private void release() {
        if (TextUtils.isEmpty(etContent.getText().toString()) && selectList.size() == 0) {
            Toast.makeText(this,"发布内容不能为空！",Toast.LENGTH_LONG).show();
            return;
        }
        if (selectList.size()>0){
            /**
             * 上传七牛
             */
            getToken();
        }else {
            mPresenter.postHumor(userId,etContent.getText().toString(),"","",tvLocation.getText().toString());
        }
    }

    private void getToken() {
        builder.show();
        //发送七牛请求
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {

                token = response.body().string();
                 Logger.e("token=="+token);
                 mHandler.sendEmptyMessage(100);
            }

            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                dialog.dismiss();
                Toast.makeText(ReleaseActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void uploadImageToQiNiu(final String path) {
        new Thread() {
            public void run() {
                // 图片上传到七牛 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
                UploadManager uploadManager = new UploadManager();
                uploadManager.put(path, null, token, new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info,
                                                 JSONObject res) {
                                // res 包含hash、key等信息，具体字段取决于上传策略的设置。
                                try {
                                    // 七牛返回的文件名
                                    String upImg = Url.PIC_URL+res.getString("key");
                                    Logger.e("upImg:"+upImg);
                                    qiNiuList.add(upImg);//将七牛返回图片的文件名添加到list集合
                                    //list集合中图片上传完成后，发送handler消息回主线程进行其他操作
                                    if (qiNiuList.size() == selectList.size()) {
                                        mHandler.sendEmptyMessage(UP_SUCCESS);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, null);
            }
        }.start();
    }

    @Subscribe
    public void onEvent(EventBusBean busBean) {
            selectList.remove(busBean.getPosition());
            releaseAdapter.addDate(selectList);
    }

    @Override
    public void requestSuccess(String msg) {
        builder.dismiss();
        setResult(RESULT_OK);
        finish();
    }




}
